import {
  getBanner,
  getRanking,
  getSongMenu
} from "../../api/home"
import debounce from "../../utils/debounce"
import querySelector from '../../utils/query-rect'

const debounceQuery = debounce(querySelector)

// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: '',
    bannerList: [],
    swiperHeight: 0,
    recommendMuisc: [],
    hotSongMenu: [],
    chineseMenu: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPageData()
  },

  // 搜索
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 获取页面初始化数据
  async getPageData() {
    // 获取轮播图数据
    getBanner().then(res => {
      this.setData({
        bannerList: res.banners
      })
    })

    // 推荐音乐
    const res = await getRanking(1)
    // console.log(res);
    this.setData({
      recommendMuisc: res.playlist.tracks.slice(0, 6)
    })

    // 热门歌单
    getSongMenu().then(res => {
      // console.log(res);
      this.setData({hotSongMenu: res.playlists})
    })

    // 华语歌单
    getSongMenu("华语").then(res => {
      // console.log(res);
      this.setData({chineseMenu: res.playlists})
    })
  },

  // 处理图片高度和轮播图高度一致
  handleImgBindLoad() {
    // console.log(debounceQuery());
    debounceQuery('.swiperImg').then(res => {
      this.setData({
        swiperHeight: res[0].height
      })
    })
  },

  // 跳转歌单详情
  navigateToDetailSongsPage(rankingName) {
    wx.navigateTo({
      url: `/pages/song-menu-detail/song-menu-detail?ranking=${rankingName}&type=rank`
    })
  },

  // 更多
  onMore(e) {
    // console.log(e.detail);
    this.navigateToDetailSongsPage(e.detail)
  },

  // 跳转歌曲详情页
  onMusicDetail(e) {
    const id = e.target.dataset.id
    if(id) {
      wx.navigateTo({
        url: '/pages/music-player/music-player?id=' + id
      })
    }
  }

})